<?php
function dataPost($post_string, $url)
{ //POST方式提交数据
    $context = array('http' => array(
        'method' => "POST",
        'header' => "Connection: close\r\n Content-Type: application/x-www-form-urlencoded\r\n User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) \r\n Accept: */*",
        'content' => $post_string));
    $stream_context = stream_context_create($context);
    $data = file_get_contents($url, false, $stream_context);
    return $data;
}

$i = 0;
$token = '';
$remindUnix = 0;
$expireTime = 0;
$conn = mysqli_connect('121.41.23.82' , 'root' , 'weicedbmojito160824','weixin_didao_wxapp');
$query = "Set Names 'utf8mb4'";
mysqli_query($conn,$query);

while (true) {
    echo "-------------------------------------------------------------------------------------------\n";
    echo date('Y-m-d H:i:s', time()) . "\tnow start\n";

    //查party信息
    $partyInfo = array();
    $query = "SELECT `id`,`begin_time_unix`,`name`,`begin_time`,`location`,`max_member` FROM didao_wxapp_party WHERE `begin_time_unix` > unix_timestamp() ";
    $result = mysqli_query($conn, $query);
    while ($row = mysqli_fetch_assoc($result)){
        $partyId = $row['id'];
        $partyInfo[$partyId] = $row;
    };
    //查用户昵称
    $users = array();
    $query = "SELECT `openid`,`nick_name` FROM didao_wxapp_users";
    $result = mysqli_query($conn, $query);
    while ($row = mysqli_fetch_assoc($result)){
        $openid = $row['openid'];
        $users[$openid] = $row['nick_name'];
    };

    //先看party参与者，这些人开启了提醒而且没有被提醒过
    $partyAttender = array();
    $query = "SELECT `party_id`,`openid`,`form_id`,`remind_picker` FROM didao_wxapp_party_attender WHERE `remind_picker`!='0' AND `is_remind`='0' AND cancel_flag='1'";
    $result = mysqli_query($conn, $query);
    while ($row = mysqli_fetch_assoc($result)){
        $openid = $row['openid'];
        $partyId = $row['party_id'];
        $formId = $row['form_id'];

        if (isset($partyInfo[$partyId])){

            $remindPicker = $row['remind_picker'];
            $beginTimeUnix = $partyInfo[$partyId]['begin_time_unix'];

            if ($expireTime < time()) {
                $tokenResult = mysqli_query($conn, "select * from weixin_token where appID='wxf2961c5a99aa520a' and expireTime > now()");
                $tokenRow = mysqli_fetch_assoc($tokenResult);
                $expireTime = strtotime($tokenRow['expireTime']);
                $token = $tokenRow['token'];
                echo "重新刷新Token".$token."\n";
            }

            switch ($remindPicker) {
                case 0:
                    $remindUnix = 0;
                    break;
                case 1:
                    $remindUnix = 300;
                    break;
                case 2:
                    $remindUnix = 900;
                    break;
                case 3:
                    $remindUnix = 1800;
                    break;
                case 4:
                    $remindUnix = 3600;
                    break;
                case 5:
                    $remindUnix = 7200;
                    break;
                case 6:
                    $remindUnix = 86400;
                    break;
                case 7:
                    $remindUnix = 172800;
                    break;
                case 8:
                    $remindUnix = 610800;
                    break;
                default:
                    $remindUnix = 0;
            }

            $d = $beginTimeUnix - time(); //D delta

            if ($remindUnix != 0  && ($d - $remindUnix) < 10 ) {
                {
                    $keyword1=$partyInfo[$partyId]['name'];
                    $keyword2=$partyInfo[$partyId]['begin_time'];
                    $keyword3=json_decode(trim($partyInfo[$partyId]['location'],'\"'),true)['name'];
                    $keyword4=$partyInfo[$partyId]['max_member'];
                    $keyword5=$users[$openid];
                }
                $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$token";

//        echo $access_token;
                $template = array(
                    'touser' => "$openid",
                    'template_id' => '4rJoVjZqi-YNzGRjuwD_Qf7Cdz58kMgvLA14v9XxbFY',
                    'form_id' => "$formId",
                    "data" => array(
                        "keyword1" => array(
                            "value" => "$keyword1",
                            "color" => "#173177"
                        ),
                        "keyword2" => array(
                            "value" => "$keyword2",
                            "color" => "#173177"
                        ),
                        "keyword3" => array(
                            "value" => "$keyword3",
                            "color" => "#173177"
                        ),
                        "keyword4" => array(
                            "value" => "$keyword4",
                            "color" => "#173177"
                        ),
                        "keyword5" => array(
                            "value" => "$keyword5",
                            "color" => "#173177"
                        ),
                    )
                );
//            print_r($template);
                $query = "UPDATE didao_wxapp_party_attender SET `is_remind`='1' WHERE `form_id` = '$formId'";
                echo $query."\n";
                mysqli_query($conn,$query);
//    echo $url;
                $request = urldecode(json_encode($template));
                $msgResult = json_decode(dataPost($request, $url), true);
                print_r($msgResult);
//        echo $row['weixinNick'];
                echo ++$i;
            }
            else{
                echo $d - $remindUnix.",等待下次查询，时间未到\n";
            }
        }else{
            $query = "UPDATE didao_wxapp_party_attender SET `cancel_flag`='0' WHERE `form_id` = '$formId'";
            echo $query."\n";
            mysqli_query($conn,$query);
            echo "聚会已过期\n";
        }
    }

    {
        echo "睡眠时间60s\n";
        sleep(60);
    }


}
/**
 * Created by PhpStorm.
 * User: a7849
 * Date: 2017/7/25
 * Time: 16:47
 */